$(function () {
    var settings = {
        async: {
            dataType: 'json',
            dataFilter: function (treeId, treeNode, response) {
                if (response.success) {
                    return response.entity;
                } else {
                    icModale(0, response.message);
                }
            },
            enable: true,
            type: 'post',
            url: baseloaction + "/admin/manage/function/ajax/listSysFunction"
        },
        check: {
            enable: true
        },
        data: {
            key: {
                name: 'functionName',
                title: 'functionName',
                functionType: 'functionType',
                functionUrl: 'functionUrl',
                showIndex: 'showIndex'
            },
            simpleData: {
                enable: true,
                idKey: 'id',
                pIdKey: 'parentId',
                rootPId: null
            }
        },
        edit: {
            drag: {
                isMove: true
            },
            enable: true,
            removeTitle: function (treeId, treeNode) {
                if (treeNode.isParent) {
                    return "删除：" + treeNode.functionName + '及其子节点';
                } else {
                    return "删除：" + treeNode.functionName;
                }
            },
            renameTitle: function (treeId, treeNode) {
                return "修改：" + treeNode.functionName;
            },
            showRemoveBtn: true,
            showRenameBtn: true
        },
        view: {
            addHoverDom: function (treeId, treeNode) {
                if(treeNode.level > 2){
                    return false;
                }
                var sObj = $("#" + treeNode.tId + "_span");
                if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0 || treeNode.level > 2){
                    return;
                }
                var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加权限' onfocus='this.blur();'></span>";
                sObj.after(addStr);
                var btn = $("#addBtn_" + treeNode.tId);

                if (btn) btn.bind("click", function () {
                    initUpdateOrAddFunction(treeNode.id,0,treeNode.level+1);
                    return false;
                });
            },
            removeHoverDom: function (treeId, treeNode) {//鼠标离开删除自定义按钮
                $("#addBtn_" + treeNode.tId).unbind().remove();
            },
            fontCss: function (treeId, treeNode) {
                if (typeof treeNode.highlight == 'undefined' || treeNode.highlight == false) {
                    return {color: "#333", "font-weight": "normal"};
                } else {
                    return {color: "#A60000", "font-weight": "bold"};
                }
            },
            showLine: true,
            selectedMulti: false
        },
        callback: {
            beforeDrop: function (treeId, treeNode, targetNode, moveType, isCopy) {
                var container = [];
                getAllNodes(treeNode, container);
                //将container按等级排序
                container.sort(function (a, b) {
                    return a.level - b.level;
                });
                var reallyLevel = 1 + container[container.length - 1].level - container[0].level;
                if ('inner' == moveType) {
                    reallyLevel += targetNode == null ? 0 : targetNode.level + 1;
                } else {
                    reallyLevel += targetNode == null ? 0 : targetNode.getParentNode() == null ? 1 : targetNode.getParentNode().level + 1;
                }
                if (reallyLevel > 4) {
                    icModale(0, '权限最多支持四级节点');
                    return false;
                }
                if ('inner' == moveType && targetNode.level == 2 && treeNode[0].functionType != 2) {
                    icModale(0, '最后一级节点只能为功能类型权限');
                    return false;
                }
                if (('prev' == moveType || 'next' == moveType) && targetNode == null && treeNode[0].functionType != 1) {
                    icModale(0, '一级节点只能为菜单类型权限');
                    return false;
                }
                /*if (targetNode.getParentNode() != null && $.trim(treeNode[0].functionUrl)) {
                    icModale(0, '非一级节点的url路径不能为空');
                    return false;
                }*/

                //拖动链上的节点id
                container = [];
                getAllNodes(treeNode, container);
                if (container.length > 0) {
                    var rawChainIds = container.map(function (node) {
                        return node.id;
                    }).join(',');
                }

                if ('inner' != moveType && targetNode != null) {
                    targetNode = targetNode.getParentNode();
                }

                //目标链上的节点id
                if (targetNode != null) {
                    var root = getRootNode(targetNode);
                    container = [];
                    getAllNodes(root, container);
                }
                $.ajax({
                    url: baseloaction + '/admin/manage/function/ajax/updateSysFunctionParent',
                    data: {
                        'functionId': treeNode[0].id,
                        'parentId': targetNode == null ? 0 : targetNode.id
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            icModale(0, response.message);
                            var zTreeObj = $.fn.zTree.getZTreeObj('function');
                            zTreeObj.moveNode(targetNode, treeNode[0], moveType, false);
                            zTreeObj.cancelSelectedNode(treeNode[0]);
                        } else {
                            icModale(0, response.message);
                        }
                    },
                    error: function () {
                        icModale(0, '系统错误，移动权限节点失败');
                    }
                });
                return false;
            },
            beforeEditName: function (treeId, treeNode) {
                initUpdateOrAddFunction(0,treeNode.id,treeNode.level);
                return false;
            },
            beforeRemove: function (treeId, treeNode) {
                var container = [];
                getAllNodes(treeNode, container);
                var ids = container.map(function (node) {
                    return node.id;
                }).join(',');
                deleteSysFunction(ids);
                return false;
            },
            onAsyncError: function () {
                icModale(0, "系统错误，权限获取失败");
            },
            onAsyncSuccess: function (event, treeId) {
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                var arr = treeObj.getNodes();
                if(arr && arr.length>0){
                    var node = arr[0];
                    treeObj.expandNode(node,true,true,true);
                }else{
                    setNotDataMsg()
                }
                initCount();
            }
        }
    };
    //如果没有权限数据这显示
    function setNotDataMsg() {
        $("#function").html('<p id="not-data-msg"><span class="c-4e fs16">亲，还没有创建权限结构~~~</span></p>');
    }
    //初始化设置权限数据
    function initCount() {
        var count = getCount("function");
        $('#function-count').html('共' + count + '个权限');
    }
    //初始化权限树
    $.fn.zTree.init($('#function'), settings);

    $('body').on('click', '#deleteBatch', function () { //批量删除权限
        var nodes = $.fn.zTree.getZTreeObj('function').getCheckedNodes(true);
        if (nodes.length == 0) {
            icModale(0, '请选择要删除的权限');
            return;
        }
        var nodeIds = nodes.filter(function (node) {
            return node.getCheckStatus().half == false;
        }).map(function (node) {
            return node.id;
        }).join(',');
        deleteSysFunction(nodeIds);
    }).on('keyup', '#search-function', function () { //搜索权限树
        var keyword = this.value;
        var treeObj = $.fn.zTree.getZTreeObj("function");
        if ($.isEmptyObject($.trim(keyword))) {
            var nodes = treeObj.getNodesByFilter(function (node) {
                return node.highlight;
            }, false);
            if (nodes.length > 0) {
                nodes.forEach(function (node) {
                    node.highlight = false;
                    treeObj.updateNode(node);
                });
            }
            return;
        }
        treeObj.getNodesByFilter(function (node) {
            return node.highlight;
        }, false).forEach(function (node) {
            node.highlight = false;
            treeObj.updateNode(node);
        });
        treeObj.getNodesByFilter(function (node) {
            return node.functionName.indexOf(keyword) != -1;
        }).forEach(function (node) {
            node.highlight = true;
            treeObj.updateNode(node);
            treeObj.expandNode(node,true,true,true);
            var parentNode = node.getParentNode();
            if(parentNode!=null){
                treeObj.expandNode(parentNode,true,true,true);
            }
        });
    }).on('click', '#add-function', function () { //添加权限
        initUpdateOrAddFunction(0,0,0);
    });

    //全选权限树
    allSelete('all-function', function (status) {
        $.fn.zTree.getZTreeObj("function").checkAllNodes(status);
    });

    //初始化添加或修改权限页面
    function initUpdateOrAddFunction(parentId,functionId,level) {
        var title = "修改资源权限";
        var url = baseloaction + "/admin/manage/function/initUpdateFunction?functionId="+functionId;
        var status = false;
        if(functionId==0){
            title = "新建资源权限"
            url = baseloaction + "/admin/manage/function/initAddFunction?parentId="+parentId;
            status = true;
        }
        url = url +"&level="+level;
        var context = "";
        $.ajax({
            url:url,
            type:'post',
            dataType:'text',
            async:false,
            success:function(result){
                context = result;
            },
            error:function(error){
                icModale(0, "系统错误，操作失败");
            }
        });
        parent.layer.open({
            type: 1,
            title: '<strong>'+title+'</strong><small class="ml10"></small>',
            shadeClose: false,
            shade: [0.3, '#000000'],
            maxmin: true, //开启最大化最小化按钮
            btn:["保存权限","取消"],
            area: ['900px', '520px'],
            content: context,
            yes: function(index, layero){
                var params = $(layero).find("form").serializeJSON();
                var _functionUrl = params.functionUrl;
                if (_functionUrl == '' || _functionUrl == null){
                    _functionUrl = " ";
                    params.functionUrl = _functionUrl;
                }
                params = JSON.stringify(params);
                $.ajax({
                    url: baseloaction +'/admin/manage/function/ajax/saveSysFunction',
                    contentType:'application/json;charset=utf-8',
                    type:'post',
                    dataType:'json',
                    data:params,
                    success:function (result) {
                        if(result.success==true){
                            var sysFunction = result.entity;
                            var treeObj = $.fn.zTree.getZTreeObj("function");
                            if(status==false){//修改节点
                                var nodeList = treeObj.getNodesByParam("id",sysFunction.id,null);
                                nodeList[0].functionName = sysFunction.functionName;
                                nodeList[0].functionType = sysFunction.functionType;
                                nodeList[0].functionUrl = sysFunction.functionUrl;
                                treeObj.updateNode(nodeList[0]);
                            }else{//添加节点
                                var parentId = result.parentId;
                                var parentNode = null;
                                if(parentId!=null){
                                    var nodeList = treeObj.getNodesByParam("id",parentId,null);
                                    if(nodeList!=null && nodeList.length > 0){
                                        parentNode = nodeList[0];
                                    }
                                }
                                var nodes = new Array();
                                nodes.push(sysFunction);
                                treeObj.addNodes(parentNode,nodes);
                                //重新初始化数量
                                initCount();
                                $("#not-data-msg").remove();
                            }
                            parent.layer.close(index);
                        }else{
                            icModale(0, result.message);
                        }
                    },
                    error:function (error) {
                        icModale(0, "系统错误，配置数据资源权限失败");
                    }
                });
            },
            success:function(index,layero){
                initSNU({
                    id:'majorInfo',
                    type:2,
                    toolsArr:null,
                    height:360,
                    gs:true,
                    video:true
                });
            }
        });
    }


    //删除系统权限
    function deleteSysFunction(functionIds) {
        icModale(2, '确认删除选中的节点？', 3, function () {
            $.ajax({
                url: baseloaction + '/admin/manage/function/ajax/deleteSysFunction',
                data: {'ids': functionIds},
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        icModale(0, response.message);
                        var zTree = $.fn.zTree.getZTreeObj('function');
                        (functionIds + '').split(',').forEach(function (id) {
                            var node = zTree.getNodeByParam('id', id, null);
                            zTree.removeNode(node);
                        });
                        initCount();
                        var count = getCount("function");
                        if(count <= 0){
                            setNotDataMsg();
                        }
                    } else {
                        icModale(0, response.message);
                    }
                },
                error: function (error) {
                    icModale(0, "系统错误，权限删除失败");
                }
            });
        });
        return true;
    }
});

/**
 * 拖动时获取所有被移动的节点
 * @param treeNodes 被拖动的节点
 * @param container 存放所有被移动的节点的数组容器
 */
function getAllNodes(treeNodes, container) {
    if (Array.isArray(treeNodes)) {
        treeNodes.forEach(function (node) {
            getAllNodes(node, container);
        });
    } else {
        if (treeNodes.isParent) {
            container.push(treeNodes);
            getAllNodes(treeNodes.children, container);
        } else {
            container.push(treeNodes);
        }
    }
}

function getRootNode(treeNode) {
    var temp = treeNode;
    while ((treeNode = treeNode.getParentNode()) != null) {
        temp = treeNode;
    }
    return temp;
}